<?php

namespace Modules\Goods\Http\Controllers\API;

use Modules\Goods\Entities\Goods;
use Illuminate\Routing\Controller;
use Modules\Goods\Entities\Category;
use Modules\Goods\Services\GoodsService;

class CategoryController extends Controller
{
    /**
     * 获取所有分类
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Category::all()->groupBy('parent_id');
        if(count($data) === 0)
            return $data;
        
        // 建立树形结构
        $root = $data[0];

        for ($i=0; $i < count($root); $i++) {
            $root_id = $root[$i]['id'];
            $root[$i]['sub'] = $data[$root_id];
        }

        return $root;
    }

    /**
     * 获取指定分类的所有子类
     *
     * @param int $parent_id 指定分类的id，root分类为0。
     * @return array 所有子类
     */
    public function list(int $parent_id = 0) {
        return Category::where('parent_id', $parent_id)
            ->where('display', true)
            ->orderBy('order')
            ->get(['id', 'title', 'desc', 'style']);
    }

    /**
     * 获取分类所有商品
     *
     * @param integer $category_id 指定分类的id
     * @param integer $limit 页面数据量，0为所有数据
     * @return void
     */
    public function getGoods(int $category_id, GoodsService $sGoods) {
        $query =  Goods::where('category_id', $category_id);
        return $sGoods->getGoodsBaseInfoPaginate($query);
    }
}
